package ltd.jdsoft.cute.prometheus;

import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import ltd.jdsoft.cute.common.extention.ExtensionLoader;
import ltd.jdsoft.cute.prometheus.spi.Monitor;

/**
 * 监控项的链式调用
 * 
 * @author zhengzhq
 *
 */
public class MonitorChain {
  private int index = 0;
  private static List<Monitor> monitorList = ExtensionLoader.getExtensionList(Monitor.class);
  private String[] labelValues = null;

  public MonitorChain(ProceedingJoinPoint joinPoint) {
    this.labelValues = getLabelValues(joinPoint);
  }

  public Object doChain(ProceedingJoinPoint joinPoint, MonitorChain chain) throws Throwable {
    if (index == monitorList.size()) {
      return joinPoint.proceed();
    }

    Monitor monitor = monitorList.get(index++);
    return monitor.process(joinPoint, chain, labelValues);
  }

  private String[] getLabelValues(ProceedingJoinPoint joinPoint) {
    String className = joinPoint.getTarget().getClass().getSimpleName();
    MethodSignature methodSign = (MethodSignature) joinPoint.getSignature();
    String methodName = methodSign.getMethod().getName();

    return new String[] {className, methodName};
  }
}
